"""
微博发布器
"""

import requests
import json
from typing import Dict, Any, Optional
from urllib.parse import urlencode

from .base import BasePublisher
from ..core.config import get_settings
from ..core.logger import app_logger

settings = get_settings()


class WeiboPublisher(BasePublisher):
    """微博发布器"""
    
    def __init__(self):
        self.api_base = "https://api.weibo.com/2"
        self.app_key = settings.WEIBO_APP_KEY
        self.app_secret = settings.WEIBO_APP_SECRET
        self.access_token = settings.WEIBO_ACCESS_TOKEN
        super().__init__()
    
    def get_platform_name(self) -> str:
        return "微博"
    
    def check_configuration(self) -> bool:
        """检查微博API配置"""
        required_configs = [
            self.app_key,
            self.app_secret,
            self.access_token
        ]
        
        if all(config for config in required_configs):
            app_logger.info("微博API配置完整")
            return True
        else:
            app_logger.warning("微博API配置不完整，将使用模拟模式")
            return False
    
    async def publish(self, content: str, **kwargs) -> Dict[str, Any]:
        """发布内容到微博"""
        
        # 验证内容
        if not self.validate_content(content, max_length=140):
            return self.format_response(False, error="内容验证失败")
        
        try:
            if self.is_configured:
                # 真实API调用
                result = await self._publish_to_weibo_api(content, **kwargs)
            else:
                # 模拟发布
                result = await self._mock_publish(content, **kwargs)
            
            if result["success"]:
                app_logger.info(f"微博发布成功: {result.get('post_id', 'mock_id')}")
            else:
                app_logger.error(f"微博发布失败: {result.get('error', '未知错误')}")
            
            return result
            
        except Exception as e:
            app_logger.error(f"微博发布异常: {e}")
            return self.format_response(False, error=str(e))
    
    async def _publish_to_weibo_api(self, content: str, **kwargs) -> Dict[str, Any]:
        """调用微博API发布内容"""
        
        url = f"{self.api_base}/statuses/update.json"
        
        params = {
            "access_token": self.access_token,
            "status": content
        }
        
        # 添加图片支持
        pic_url = kwargs.get("pic_url")
        if pic_url:
            params["pic"] = pic_url
        
        try:
            response = requests.post(url, data=params, timeout=30)
            
            if response.status_code == 200:
                data = response.json()
                return self.format_response(True, {
                    "post_id": str(data.get("id", "")),
                    "created_at": data.get("created_at", ""),
                    "text": data.get("text", ""),
                    "url": f"https://weibo.com/{data.get('user', {}).get('id', '')}/{data.get('id', '')}"
                })
            else:
                error_data = response.json() if response.content else {}
                error_msg = error_data.get("error", f"HTTP {response.status_code}")
                return self.format_response(False, error=error_msg)
                
        except Exception as e:
            return self.format_response(False, error=f"API调用失败: {e}")
    
    async def _mock_publish(self, content: str, **kwargs) -> Dict[str, Any]:
        """模拟发布（用于测试）"""
        
        import time
        mock_id = f"wb_{int(time.time())}"
        
        return self.format_response(True, {
            "post_id": mock_id,
            "created_at": "2024-01-01 12:00:00",
            "text": content,
            "url": f"https://weibo.com/mock/{mock_id}",
            "note": "这是模拟发布，未实际发送到微博"
        })
    
    async def delete_post(self, post_id: str) -> bool:
        """删除微博"""
        
        if not self.is_configured:
            app_logger.info(f"模拟删除微博: {post_id}")
            return True
        
        try:
            url = f"{self.api_base}/statuses/destroy.json"
            params = {
                "access_token": self.access_token,
                "id": post_id
            }
            
            response = requests.post(url, data=params, timeout=30)
            
            if response.status_code == 200:
                app_logger.info(f"微博删除成功: {post_id}")
                return True
            else:
                app_logger.error(f"微博删除失败: HTTP {response.status_code}")
                return False
                
        except Exception as e:
            app_logger.error(f"删除微博异常: {e}")
            return False
    
    async def get_post_status(self, post_id: str) -> Dict[str, Any]:
        """获取微博状态"""
        
        if not self.is_configured:
            return {
                "exists": True,
                "status": "published",
                "note": "模拟状态"
            }
        
        try:
            url = f"{self.api_base}/statuses/show.json"
            params = {
                "access_token": self.access_token,
                "id": post_id
            }
            
            response = requests.get(url, params=params, timeout=30)
            
            if response.status_code == 200:
                data = response.json()
                return {
                    "exists": True,
                    "status": "published",
                    "created_at": data.get("created_at", ""),
                    "text": data.get("text", ""),
                    "reposts_count": data.get("reposts_count", 0),
                    "comments_count": data.get("comments_count", 0),
                    "attitudes_count": data.get("attitudes_count", 0)
                }
            else:
                return {
                    "exists": False,
                    "status": "not_found"
                }
                
        except Exception as e:
            app_logger.error(f"获取微博状态异常: {e}")
            return {
                "exists": False,
                "status": "error",
                "error": str(e)
            }
    
    async def test_connection(self) -> bool:
        """测试微博API连接"""
        
        if not self.is_configured:
            return True  # 模拟模式总是可用
        
        try:
            url = f"{self.api_base}/account/verify_credentials.json"
            params = {"access_token": self.access_token}
            
            response = requests.get(url, params=params, timeout=10)
            
            if response.status_code == 200:
                app_logger.info("微博API连接测试成功")
                return True
            else:
                app_logger.error(f"微博API连接测试失败: HTTP {response.status_code}")
                return False
                
        except Exception as e:
            app_logger.error(f"微博API连接测试异常: {e}")
            return False